import java.util.*;
import java.io.Serializable;
import java.io.IOException;
import javax.swing.JFileChooser;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;

/*This class is serilizeable and wires and read itself to and from a file, handleing our loading and saving*/
public class Save implements Serializable
{
  public static String filePath = "";
  
  public static void Save(boolean SaveAs) {
    //General saving method; where the program goes to save if the user clicks "Save"
    //and has saved at least once before
    if(filePath.isEmpty() || SaveAs)
      filePath = GetSaveLocation();
    if(filePath.isEmpty())
      return;
    try {
     FileOutputStream filename = new FileOutputStream(filePath);
     ObjectOutputStream save = new ObjectOutputStream(filename); // set the location up to save
     save.writeObject(SimState.CaptureState()); // write to the file
     save.close(); // all done
     }
    
    catch(IOException e) {
     e.printStackTrace();
     }
  }
 /* 
  public static void SaveAs() {
    //Special saving method; where the program goes if the user clicks "Save As" or
    //the user clicks "Save" and has not saved at least once before
     filePath = GetSaveLocation();
     Save();
     }
 */
  public static void Load() {
    //General loading method; this is where the program goes to resume from a previously-saved state
    filePath = GetLoadLocation();
    if(filePath.isEmpty())
      return;
    SimState state = null;
    
    try {
      FileInputStream filename = new FileInputStream(filePath);
      ObjectInputStream load = new ObjectInputStream(filename);
      state = (SimState)load.readObject();
      }
    catch(IOException ex) {
      ex.printStackTrace();
      }
    catch(ClassNotFoundException ex) {
      ex.printStackTrace();
      }
    
    state.SetState();
   }
    
  public static String GetSaveLocation() {
    //Method that brings up dialog box for user to specify save location
    final JFileChooser fc = new JFileChooser();
    int returnVal = fc.showSaveDialog(SimulationConstants.mainUI);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                return file.getAbsolutePath() + ".bob";
      }
    return "";
  }
  
  public static String GetLoadLocation() {
    //Method that brings up dialog box for user to specify load location
    final JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(SimulationConstants.mainUI);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                return file.getAbsolutePath();
      }
    return "";
  }
  
  public static boolean QuerySave() { // ask the user if they wish to save the current simulation
    return true;
  }
}